package com.cetcs.kmga.dataManager.service.impl.dataManager;

import com.cetcs.kmga.common.Constant;
import com.cetcs.kmga.common.Data;
import com.cetcs.kmga.common.Page;
import com.cetcs.kmga.dataManager.dao.mybatis.ClientDBMapper;
import com.cetcs.kmga.dataManager.dao.mybatis.ResourceTrafficMapper;
import com.cetcs.kmga.dataManager.entity.dataManager.ClientDB;
import com.cetcs.kmga.dataManager.entity.dataManager.vo.*;
import com.cetcs.kmga.dataManager.entity.global.AlarmCode;
import com.cetcs.kmga.dataManager.global.DataManagerConstants;
import com.cetcs.kmga.dataManager.global.ResLogType;
import com.cetcs.kmga.dataManager.service.dataManager.TrafficStatisticService;
import com.cetcs.kmga.dataManager.util.CommonUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mysql.jdbc.log.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 流量统计Service,所有数据都是数据库查询的实时数据<br></>
 * 该实现还有一个兄弟类,他们实现同一个接口,但数据是模拟数据,不是实时数据,实时数据来源于数据库
 * Created by root on 2017/10/11.
 */
@Service("trafficStatisticRealService")
public class TrafficStatisticServiceRealImpl implements TrafficStatisticService {

    @Autowired
    private ResourceTrafficMapper resourceTrafficMapper;
    @Autowired
    private ClientDBMapper clientDBMapper;

    @Override
    public Page findResourcetraffic(int pageNumber, int pageSize, String keyword,String id) {
        try {
//            PageList<ResourceTrafficVo> resrcs =  resourceTrafficMapper.findResourceTrafficOfDay(new PageBounds(pageNumber, pageSize),keyword);
//            Page ret = new Page(resrcs);
//            for(ResourceTrafficVo resrc : resrcs){
//                ResourceTrafficVi vi = resourceTrafficMapper.findAvgOfResourceTraffic(resrc.getId());
//                if(vi != null){
//                    resrc.getOutNum().setAvgNum(vi.getOut_num());
//                    resrc.getInNum().setAvgNum(vi.getIn_num());
//                    resrc.getTotalNum().setAvgNum(vi.getTotal_num());
//                    resrc.resetNumState();
//                }
//            }
            //id的标志位
            boolean isExit = false;
            if(id==null||"".equals(id.trim())){
                //如果id为空 则 存在
                isExit = true;
            }
            PageList<ResourceTrafficTempVo> resrcs =  resourceTrafficMapper.findResourceTrafficOfDay(new PageBounds(pageNumber, pageSize),keyword);
            Page ret = new Page(resrcs);
            List<ResourceTrafficVo> resourceTrafficVos = Lists.newArrayList();
            for(ResourceTrafficTempVo resrc : resrcs){
                ResourceTrafficVo resourceTrafficVo = new ResourceTrafficVo();
                resourceTrafficVo.setId(resrc.getId());
                resourceTrafficVo.setName(resrc.getName());
                resourceTrafficVo.setIp(resrc.getIp());
                resourceTrafficVo.setClientIpAmout(resrc.getClientIpAmout());
                resourceTrafficVo.setResrcTypeName(resrc.getResrcTypeName());
                resourceTrafficVo.setTotalNum(Double.valueOf(resrc.getTotalNum().split("/")[0]),Double.valueOf(resrc.getTotalNum().split("/")[1]));
                resourceTrafficVo.setOutNum(Double.valueOf(resrc.getOutNum().split("/")[0]),Double.valueOf(resrc.getOutNum().split("/")[1]));
                resourceTrafficVo.setInNum(Double.valueOf(resrc.getInNum().split("/")[0]),Double.valueOf(resrc.getInNum().split("/")[1]));
                if(id!=null && id.equals(String.valueOf(resrc.getId()))){
                    //如果存在 则将 数据放在首位
                    isExit = true;
                    resourceTrafficVos.add(0,resourceTrafficVo);
                }else{
                    resourceTrafficVos.add(resourceTrafficVo);
                }
            }
            //如果不存在 id  则需要将数据取出来
            if(!isExit) {
                ResourceTrafficTempVo resourceTrafficTempVo = resourceTrafficMapper.findResourceTrafficOfDayById(id);
                if(resourceTrafficTempVo!=null) {
                    ResourceTrafficVo resourceTrafficVo = new ResourceTrafficVo();
                    resourceTrafficVo.setId(resourceTrafficTempVo.getId());
                    resourceTrafficVo.setName(resourceTrafficTempVo.getName());
                    resourceTrafficVo.setIp(resourceTrafficTempVo.getIp());
                    resourceTrafficVo.setClientIpAmout(resourceTrafficTempVo.getClientIpAmout());
                    resourceTrafficVo.setResrcTypeName(resourceTrafficTempVo.getResrcTypeName());
                    resourceTrafficVo.setTotalNum(Double.valueOf(resourceTrafficTempVo.getTotalNum().split("/")[0]), Double.valueOf(resourceTrafficTempVo.getTotalNum().split("/")[1]));
                    resourceTrafficVo.setOutNum(Double.valueOf(resourceTrafficTempVo.getOutNum().split("/")[0]), Double.valueOf(resourceTrafficTempVo.getOutNum().split("/")[1]));
                    resourceTrafficVo.setInNum(Double.valueOf(resourceTrafficTempVo.getInNum().split("/")[0]), Double.valueOf(resourceTrafficTempVo.getInNum().split("/")[1]));
                    resourceTrafficVos.remove(resourceTrafficVos.size() - 1);
                    resourceTrafficVos.add(0, resourceTrafficVo);
                }else{
//                    throw new Exception("数据出错 该ID不存在");
                }
            }

            ret.setContent(resourceTrafficVos);
            return ret;
        }catch (Exception e){
            e.printStackTrace();return null;}
    }

    @Override
    public List<HistogramChartVo> findTrafficStatistic(Integer resourceId) {
        try{
            //查询所有的统计
            List<HistogramChartVo> ret = new LinkedList<>();
            List<String> xaxis = Arrays.asList("今日","平均","峰值");

            //今日
            ResourceTrafficVi today = resourceTrafficMapper.findAvgOfResourceTraffic(resourceId);
            //峰值 和 平均
            Map avgAndMax = resourceTrafficMapper.findAvgAndMaxTrafficOfAllResource(resourceId);

            HistogramChartVo outNum = new HistogramChartVo();
            outNum.setName("读取流量");
            outNum.setXaxis(xaxis);
            List<String> outNumDatas = Arrays.asList(String.valueOf(today.getOut_num()),
                    String.valueOf(avgAndMax.get("out_num_avg")),
                    String.valueOf(avgAndMax.get("out_num_max")));
            outNum.setYdata(outNumDatas);
            ret.add(outNum);

            HistogramChartVo inNum = new HistogramChartVo();
            inNum.setName("写入流量");
            inNum.setXaxis(xaxis);
            List<String> inNumDatas = Arrays.asList(String.valueOf(today.getIn_num()),
                    String.valueOf(avgAndMax.get("in_num_avg")),
                    String.valueOf(avgAndMax.get("in_num_max")));
            inNum.setYdata(inNumDatas);
            ret.add(inNum);

            HistogramChartVo ipNum = new HistogramChartVo();
            ipNum.setName("访问IP量");
            ipNum.setXaxis(xaxis);
            List<String> ipNumDatas = Arrays.asList(String.valueOf(today.getIp_num()),
                    String.valueOf(avgAndMax.get("ip_num_avg")),
                    String.valueOf(avgAndMax.get("ip_num_max")));
            ipNum.setYdata(ipNumDatas);
            ret.add(ipNum);
            return ret;
        }catch (Exception e){
            e.printStackTrace();
            return null;}
    }

    @Override
    public MultiLineChartVo findAccessAmount(int timeCycle, Integer resourceId) {
        try{
            //准备"读取" 和 "写入" 两条折线
            MultiLineChartVo ret = new MultiLineChartVo();
            ret.setName("流量趋势");
            MultiLineChartVo.YdataFormat outData = new MultiLineChartVo.YdataFormat();
            outData.setName("读取");
            ret.getDatas().add(outData);
            MultiLineChartVo.YdataFormat inData = new MultiLineChartVo.YdataFormat();
            inData.setName("写入");
            ret.getDatas().add(inData);

            //查数据库
            List<ResourceTrafficVi> datas = null;
            if(resourceId == null || resourceId.intValue() == 0){//所有资源
                datas = resourceTrafficMapper.findAllAccessNum(timeCycle);
            }else{
                datas = resourceTrafficMapper.findAllAccessNumOfResrc(timeCycle,resourceId.intValue());
            }

            //封装 横坐标
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            //时间map对象
            Map<String,Integer> dateMap = Maps.newHashMap();
            String startTime;
            String endTime;
            String endString = "";
            List<String> xData = Lists.newArrayList();
            List<String> inDatas = Lists.newArrayList();
            List<String> outDatas = Lists.newArrayList();
            SimpleDateFormat simpleDateFormat;
            simpleDateFormat = new SimpleDateFormat("");
            //数据项
            switch (timeCycle){
                case 1:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.DATE,-1);
                    endString = ":00:00";
                    break;
                case 2:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.MONTH,-1);
                    endString = "";
                    break;
                case 3:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.YEAR,-1);
                    endString = "";
                break;
                default:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.DATE,-1);
                    endString = ":00:00";
                    break;
            }

            int i = 0;
            while(true){
                if(simpleDateFormat.format(calendar.getTime()).equals(endTime)){
                    inDatas.add("0");
                    outDatas.add("0");
                    xData.add(simpleDateFormat.format(calendar.getTime()) + endString);
                    dateMap.put(simpleDateFormat.format(calendar.getTime()),i);
                    break;
                }
                inDatas.add("0");
                outDatas.add("0");
                xData.add(simpleDateFormat.format(calendar.getTime()) + endString);
                dateMap.put(simpleDateFormat.format(calendar.getTime()),i);
                calendar.add(timeCycle==1?Calendar.HOUR:timeCycle==2?Calendar.DATE:Calendar.MONTH, 1);
                i++;
            }

            ret.setxAxis(xData);
            //组装结果
//            for(ResourceTrafficVi data : datas){
//                ret.getxAxis().add(data.getTime_str());
//                outData.getData().add(String.valueOf(data.getOut_num()));
//                inData.getData().add(String.valueOf(data.getIn_num()));
//            }
            //组装结果
            for(ResourceTrafficVi data : datas){
                if(dateMap.get(data.getTime_str())!=null) {
                    int index = dateMap.get(data.getTime_str());
                    inDatas.remove(index);
                    inDatas.add(index, String.valueOf(data.getIn_num()));
                    outDatas.remove(index);
                    outDatas.add(index, String.valueOf(data.getOut_num()));
                }
            }
            inData.setData(inDatas);
            outData.setData(outDatas);
            return ret;
        }catch (Exception e){
            e.printStackTrace();
            return null;}
    }

    @Override
    public MultiLineChartVo findAccessTimes(int timeCycle, Integer resourceId) {
        try{
            MultiLineChartVo ret = new MultiLineChartVo();
            ret.setName("流量趋势");
            MultiLineChartVo.YdataFormat ydata = new MultiLineChartVo.YdataFormat();
            ydata.setName("访问次数");
            ret.setDatas(Arrays.asList(ydata));

            //从数据库查询数据并填充，访问次数只有一条折线
            List<ResourceTrafficVi> datas = null;
            if(resourceId == null || resourceId.intValue() == 0){//所有资源
                datas = resourceTrafficMapper.findAllAccessTimes(timeCycle);
            }else{
                datas = resourceTrafficMapper.findAccessTimesOfResource(timeCycle,resourceId.intValue());
            }
            //组装结果

            //封装 横坐标
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            //时间map对象
            Map<String,Integer> dateMap = Maps.newHashMap();
            String startTime;
            String endTime;
            String endString = "";
            List<String> xData = Lists.newArrayList();
            List<String> inDatas = Lists.newArrayList();
            List<String> outDatas = Lists.newArrayList();
            SimpleDateFormat simpleDateFormat;
            simpleDateFormat = new SimpleDateFormat("");
            //数据项
            switch (timeCycle){
                case 1:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.DATE,-1);
                    endString = ":00:00";
                    break;
                case 2:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.MONTH,-1);
                    endString = "";
                    break;
                case 3:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.YEAR,-1);
                    endString = "";
                    break;
                default:
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                    endTime = simpleDateFormat.format(calendar.getTime());
                    calendar.add(Calendar.DATE,-1);
                    endString = ":00:00";
                    break;
            }

            int i = 0;
            while(true){
                if(simpleDateFormat.format(calendar.getTime()).equals(endTime)){
                    inDatas.add("0");
                    xData.add(simpleDateFormat.format(calendar.getTime()) + endString);
                    dateMap.put(simpleDateFormat.format(calendar.getTime()),i);
                    break;
                }
                inDatas.add("0");
                xData.add(simpleDateFormat.format(calendar.getTime()) + endString);
                dateMap.put(simpleDateFormat.format(calendar.getTime()),i);
                calendar.add(timeCycle==1?Calendar.HOUR:timeCycle==2?Calendar.DATE:Calendar.MONTH, 1);
                i++;
            }

            ret.setxAxis(xData);
            //组装结果
            for(ResourceTrafficVi data : datas){
                if(dateMap.get(data.getTime_str())!=null) {
                    int index = dateMap.get(data.getTime_str());
                    inDatas.remove(index);
                    inDatas.add(index, String.valueOf(data.getAccess_num()));
                }
            }
            ydata.setData(inDatas);
            return ret;



//            for(ResourceTrafficVi data : datas){
//                ret.getxAxis().add(data.getTime_str());
//                ydata.getData().add(String.valueOf(data.getAccess_num()));
//            }
//            return ret;
        }catch (Exception e){
            e.printStackTrace();
            return null;}
    }

    @Override
    public Page findIpOfResource(int resrc_id,String type,int pageNumber, int pageSize,String keyword){
        try{
            PageList<TrafficResrcIpTodayView> list=null;
            if(!StringUtils.isEmpty(type)&& ResLogType.FTPCJRZ.toString().equals(type)){
                list = resourceTrafficMapper.findIpOfAppTraffic(new PageBounds(pageNumber, pageSize),resrc_id);
            }else {
                list = resourceTrafficMapper.findIpOfResourceTraffic(new PageBounds(pageNumber, pageSize),resrc_id,keyword);
            }
            int i=(pageNumber-1)*pageSize+1;
            for(TrafficResrcIpTodayView item : list){
                item.setSerId(i++);
            }
            return new Page(list);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //==================================yyangs====start=========================//

    /**
     * 获得数据库直连客户端列表（未知、合法）
     * @param dataMap
     */
    @Override
    public ClientForDBVo getClientListForDatabaseDirectConnection(Data dataMap){
        ClientForDBVo clientForDBVo = new ClientForDBVo();
        //查询 客户端
        List<ClientDB> clientDBS = clientDBMapper.getClientDBByCondition(dataMap);
        //根据
        Map<Integer, List<ClientDB>> map = new LinkedHashMap<Integer, List<ClientDB>>();
        CommonUtils.listGroup2Map(clientDBS, map, ClientDB.class, "getType_code");// 输入方法名
        //封装 合法的
        ClientTreeForDBVo legalTerminal = new ClientTreeForDBVo();
        legalTerminal.setId("A1");
        legalTerminal.setName("数据库直连终端（合法）");
        legalTerminal.setNumber(map.get(1)!=null?map.get(1).size():0);
        List<ResourceTreeDataObjectVo> itemLegalTerminal = Lists.newArrayList();
        if(map.get(1)!=null) {
            for (ClientDB c : map.get(1)) {
                ResourceTreeDataObjectVo resourceTreeDataObjectVo = new ResourceTreeDataObjectVo();
                resourceTreeDataObjectVo.setId("B"+c.getIp().replace(".","_"));
                resourceTreeDataObjectVo.setName(c.getName() == null ? c.getIp() : c.getName());
                resourceTreeDataObjectVo.setIp(c.getIp());
                itemLegalTerminal.add(resourceTreeDataObjectVo);
            }
        }
        legalTerminal.setItem(itemLegalTerminal);
        List<ClientTreeForDBVo> clientTreeForDBVos = Lists.newArrayList();
        clientTreeForDBVos.add(legalTerminal);
        clientForDBVo.setLegalTerminal(clientTreeForDBVos);
        //封装未知的
        ClientTreeForDBVo illegalTerminal = new ClientTreeForDBVo();
        illegalTerminal.setId("A0");
        illegalTerminal.setName("数据库直连终端（未知）");
        List<ResourceTreeDataObjectVo> itemIllegalTerminal = Lists.newArrayList();
        List<ResourceTreeDataObjectVo> newItemIllegalTerminal = Lists.newArrayList();
        if(map.get(0)!=null) {
            for (ClientDB c : map.get(0)) {
                ResourceTreeDataObjectVo resourceTreeDataObjectVo = new ResourceTreeDataObjectVo();
                resourceTreeDataObjectVo.setId("B" + c.getIp().replace(".","_"));
                resourceTreeDataObjectVo.setName(c.getName() == null ? c.getIp() : c.getName());
                resourceTreeDataObjectVo.setIp(c.getIp());
                if(c.getDeal_flag()==0){
                    newItemIllegalTerminal.add(resourceTreeDataObjectVo);
                }else{
                    itemIllegalTerminal.add(resourceTreeDataObjectVo);
                }
            }
        }
        //获取数量
        Data params = new Data();
        params.put("lastSearchTime", DataManagerConstants.CLIENT_SEARCH_TIME);
        params.put("cluster_id_null",1);
        params.put("type_code",0);
        if(dataMap.get("refresh")!=null) {
            DataManagerConstants.CLIENT_SEARCH_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        }
        List<ClientDB> clientDBList = clientDBMapper.getClientDBByCondition(params);
        illegalTerminal.setItem(itemIllegalTerminal);
        illegalTerminal.setNewItem(newItemIllegalTerminal);
        illegalTerminal.setNumber(newItemIllegalTerminal.size()>0?newItemIllegalTerminal.size():0);
        clientForDBVo.setIllegalTerminal(illegalTerminal);
        return clientForDBVo;
    }

    /**
     * 更新客户端
     * @param dataMap
     * @return
     */
    @Override
    public Integer updateClientInfo(Data dataMap) {
        //先要判断 名称是否重复
        if(dataMap.get("name")!=null) {
            Data params = new Data();
            params.put("ipF",dataMap.get("ip"));
            params.put("name", dataMap.get("name"));
            List<ClientDB> clientDBS = clientDBMapper.getClientDBByCondition(params);

            if (clientDBS.size() > 0) {
                return 0;
            } else {
                return clientDBMapper.updateClientDB(dataMap);
            }
        }else{
            return clientDBMapper.updateClientDB(dataMap);
        }
    }

    /**
     * 查询客户端信息  通过ip
     * @param dataMap
     * @return
     */
    @Override
    public ClientDB getClientInfoById(Data dataMap) {
        List<ClientDB> clientDBS = clientDBMapper.getClientDBByCondition(dataMap);
        return clientDBS!=null&&clientDBS.size()>0?clientDBS.get(0):null;

    }


    //==================================yyangs====end=========================//
}
